package com.keshihao.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keshihao.eduservice.entity.EduSubject;
import com.keshihao.eduservice.entity.excel.SubjectData;
import com.keshihao.eduservice.entity.subject.OneSubject;
import com.keshihao.eduservice.entity.subject.TwoSubject;
import com.keshihao.eduservice.listener.SubjectExcelListener;
import com.keshihao.eduservice.mapper.EduSubjectMapper;
import com.keshihao.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author keshihao
 * @since 2020-05-22
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    // 添加课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {

            InputStream inputStream = file.getInputStream();

            EasyExcel.read(inputStream, SubjectData.class ,new SubjectExcelListener(subjectService)).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 课程分类列表（树形）
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // 1 查询所有一级分类
        List<EduSubject> allOneSubject = baseMapper.selectList(new QueryWrapper<EduSubject>().eq("parent_id", "0"));

        // 2 查询所有二级分类
        List<EduSubject> allTwoSubject = baseMapper.selectList(new QueryWrapper<EduSubject>().ne("parent_id", "0"));

        // 创建list集合，用于存储最终封装的数据。
        List<OneSubject> list = new ArrayList<>();

        // 封装一级分类
        for (EduSubject eduSubject : allOneSubject) {
            OneSubject oneSubject = new OneSubject();
//            oneSubject.setId(eduSubject.getId());
//            oneSubject.setTitle(eduSubject.getTitle());
            BeanUtils.copyProperties(eduSubject,oneSubject);


            // 在一级分类循环遍历查询所有的二级分类
            // 创建list集合封装每一个一级分类的二级分类
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            // 遍历二级分类list集合
            for (EduSubject subject : allTwoSubject) {
                if (eduSubject.getId().equals(subject.getParentId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(subject,twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }

            oneSubject.setChildren(twoSubjectList);

            list.add(oneSubject);

        }

        return list;
    }

}
